package vn.njai.thousand_english_word.Activity;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import butterknife.ButterKnife;
import butterknife.InjectView;
import vn.njai.thousand_english_word.Entities.HistoryNodeItem;
import vn.njai.thousand_english_word.R;
import vn.njai.thousand_english_word.Utils.DataManager;

import java.util.ArrayList;

/**
 * Created by VUONG on 12/14/2014.
 */
public class HistoryActivity extends ActionBarActivity implements  MediaPlayer.OnCompletionListener{
    private String TAG = "HistoryActivity";
    private Context mContext;
    private Adapter mAdapter;

    @InjectView(R.id.toolbar) public Toolbar mToolbar;
    @InjectView(R.id.listNode) public ListView mListNode;

    public static void start(Context context) {
        Intent intent = new Intent(context,HistoryActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);
        mContext = getApplicationContext();
        init();
    }

    public void init(){
        ButterKnife.inject(this);
        initActionBar();
        mAdapter = new Adapter();
        mListNode.setAdapter(mAdapter);
        load();
        mListNode.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ViewGroup viewGroup  = (ViewGroup) view.findViewById(R.id.viewShow);
                if(viewGroup.getVisibility() == View.GONE) {
                    viewGroup.setVisibility(View.VISIBLE);
                    mAdapter.getItem(i).mIsShow = true;
                }else{
                    viewGroup.setVisibility(View.GONE);
                    mAdapter.getItem(i).mIsShow = false;
                }
            }
        });
        mListNode.setItemsCanFocus(true);
    }

    public void load(){
        ArrayList<HistoryNodeItem> nodeItems = new ArrayList<HistoryNodeItem>();
        for(int i = 0;i< DataManager.getInstance().mHistoryData.mListHistory.size();i++){
            HistoryNodeItem recent = new HistoryNodeItem(DataManager.getInstance().getNodeAt(DataManager.getInstance().mHistoryData.mListHistory.get(i)));
            nodeItems.add(recent);
        }
        mAdapter.addAll(nodeItems);
    }

    private void initActionBar(){
        mToolbar.setTitle(getString(R.string.actionbar_title_history));
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_back);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        mediaPlayer.release();
    }

    public class Adapter extends ArrayAdapter<HistoryNodeItem> {

        public class ViewHolder{
            @InjectView(R.id.txtWord) public TextView word;
            @InjectView(R.id.viewShow) public View showView;
            @InjectView(R.id.viewAll) public View allView;
            @InjectView(R.id.txtRank) public TextView rank;
            @InjectView(R.id.txtPhonetic) public TextView phonetic;
            @InjectView(R.id.txtMeans) public TextView mean;
            @InjectView(R.id.btnSound) public ImageButton btnSound;
            @InjectView(R.id.txtType) public TextView txtType;
            public ViewHolder(View view){
                ButterKnife.inject(this,view);
            }
        }

        public Adapter() {
            super(mContext, 0, new ArrayList<HistoryNodeItem>());
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // Get the data item for this position
            View view = convertView;
            final ViewHolder viewHolder;
            final HistoryNodeItem item = getItem(position);
            // Check if an existing view is being reused, otherwise inflate the view
            if (view == null) {
                view = LayoutInflater.from(getContext()).inflate(R.layout.custom_node_history, parent, false);
                viewHolder = new ViewHolder(view);
                view.setTag(viewHolder);
            }else{
                viewHolder = (ViewHolder) view.getTag();
            }
            viewHolder.word.setText(item.mWord);
            viewHolder.rank.setText(item.mRank + "");
            viewHolder.phonetic.setText(item.mPhonetic);
            viewHolder.mean.setText(item.mMeans);
            if(item.mIsShow == true){
                viewHolder.showView.setVisibility(View.VISIBLE);
            }else{
                viewHolder.showView.setVisibility(View.GONE);
            }
            viewHolder.txtType.setText(item.mType);
            viewHolder.allView.setBackgroundColor(item.mColor);
            viewHolder.btnSound.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Handler handler = new Handler();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            try {

                                MediaPlayer mediaPlayer = new MediaPlayer();
                                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                                String url = "http://soundoftext.com/audio/English/" + item.mWord.toLowerCase() + ".mp3";
                                DataManager.getInstance().loadVolume();
                                mediaPlayer.setVolume((float)DataManager.getInstance().mVolume/100,(float)DataManager.getInstance().mVolume/100);
                                mediaPlayer.setDataSource(url);
                                mediaPlayer.prepare(); // might take long! (for buffering, etc)
                                mediaPlayer.start();
                            }catch (Exception ex){

                            }
                        }
                    });
                }
            });
            return view;
        }
    }
}
